/**
 * @author xuyh0817
 * @email xuyh0817@foxmail.com
 * @date 2022-03-15 22:57
 * @version 2.0.0
 * @doc todo
 * @website todo
 * @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
 */
import { cloneDeep } from 'lodash'
import { copyFormOption, getFormOption, randomString, removeFormOption } from '../utils'

export default {
  name: 'XRenderDesignMixin',
  inject: ['xDesignForm'],
  methods: {
    designUpdateCurrentId(item) {
      const { xDesignForm } = this
      xDesignForm.currentId = item.id
    },
    // 删除
    designRemoveHandler(item, prevItem) {
      const { xDesignForm } = this
      removeFormOption(xDesignForm.formOptions, item.id)
      if (!!prevItem) {
        const formOption = getFormOption(xDesignForm.formOptions, prevItem.id)
        // 设置当前项
        this.designUpdateCurrentId(formOption)
      }
    },
    designCopyHandler(item) {
      const { xDesignForm, id } = this
      const option = cloneDeep(item)
      if (!option.isLayout) {
        option.formItem.prop = 'key_' + Date.now()
      }
      // 重新命名name,针对checkbox radio
      if (option.attrs.name) {
        option.attrs.name = Date.now() + ''
      }
      // 设置新的id
      option.id = randomString()
      // 父级id
      option.parentId = id || ''
      // 添加
      copyFormOption(xDesignForm.formOptions, item.id, option)
      // 设置当前项
      this.designUpdateCurrentId(option)
    },
    // 新增项
    designAddHandler({ newIndex }, formOptions) {
      const { id } = this
      const formOption = formOptions[newIndex]
      if (!!id) {
        this.$set(formOption, 'parentId', id)
      }
      this.designUpdateCurrentId(formOption)
    },
    // 移动结束
    designMoveEndHandler({ newIndex }, formOptions) {
      this.designUpdateCurrentId(formOptions[newIndex])
    },
    // 点击选中
    designSelectedHandler(item) {
      this.designUpdateCurrentId(item)
    }
  }
}
